package dao;

import database.DataBase;
import interfaces.VareInterface;
import interfaces.VaregruppeInterface;
import java.rmi.RemoteException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.Vare;
import model.VareGruppe;

public class Varegruppe_DAO {

    private DataBase conn;
    private static Varegruppe_DAO vg_dao;

    public Varegruppe_DAO() {
        this.conn = DataBase.getInstance();
    }

    public static Varegruppe_DAO getInstance() {
        if (vg_dao == null) {
            vg_dao = new Varegruppe_DAO();
        }
        return vg_dao;
    }

    public ArrayList<VaregruppeInterface> hentVaregrupper() throws SQLException, RemoteException {
        ArrayList<VaregruppeInterface> varegrupper = new ArrayList<>();

        ResultSet rs = null;

        /* Hent alle vare grupper */
        String sql = "call `hent varegrupper`();";

        System.out.println("sql   " + sql);
        rs = conn.getResult(sql);
        while (rs.next()) /* Hent samtlige varegrupper .. */ {
            VaregruppeInterface vg = new VareGruppe(rs.getString("navn"));
            varegrupper.add(vg);
        }

        return varegrupper;
    }

    public ArrayList<VareInterface> hentVarer(String firma, String vg) throws SQLException, RemoteException {

        ArrayList<VareInterface> vareListe = new ArrayList();
        Vare vare = null;
        ResultSet rs = null;

        String sql = "call `hent rabatvare`('" + firma + "', '" + vg + "');";
        rs = conn.getResult(sql);
        while (rs.next()) {
            vare = new Vare(rs.getString("navn"), rs.getDouble("rabatpris"), rs.getInt("antal"), rs.getString("vgruppe"));
            vareListe.add(vare);

        }
        if (vareListe.isEmpty()) {
            String sql2 = "call `hent varer`('" + vg + "');";
            rs = conn.getResult(sql2);
            while (rs.next()) {
                vare = new Vare(rs.getString("navn"), rs.getDouble("pris"), rs.getInt("antal"), rs.getString("vgruppe"));
                vareListe.add(vare);
            }
        }
        return vareListe;
    }
}
